package com.youdoneed.friends.livechat;

import com.youdoneed.base.application.ResultMessage;
import com.youdoneed.base.common.OkHttpUtils;
import com.youdoneed.friends.common.config.HuanXinConfig;
import com.youdoneed.friends.common.util.HuanXinUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Ewing
 * @since 2017-04-21
 **/
@RestController
@RequestMapping(value = "/user")
@Api(value = "聊天模块环信群组操作控制器", description = "聊天模块环信群组操作控制器")
public class GroupUserController {
    private static final Logger logger = LoggerFactory.getLogger(GroupUserController.class);

    @RequestMapping(value = "/getGroupUser", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "获取 APP 中群组（可分页）", value = "获取 APP 中群组（可分页）")
    public ResultMessage<String> getGroupUser(
            @ApiParam("预期获取的记录数") @RequestParam String limit,
            @ApiParam("上次请求返回的游标") @RequestParam(required = false) String cursor) {
        String apiUrl = HuanXinConfig.url + "chatgroups?limit=" + limit;
        if (null != cursor) {
            apiUrl = apiUrl + "&cursor=" + cursor;
        }
        try {
            String token = HuanXinUtil.getAccessToken();
            String result = OkHttpUtils.get(apiUrl)
                    .header("Authorization", "Bearer " + token)
                    .callForString();
            return new ResultMessage<>(result);
        } catch (Exception e) {
            logger.error("获取 APP 中的群组失败：" + e);
            return new ResultMessage<String>().toFailure("获取 APP 中的群组失败！");
        }
    }

    @RequestMapping(value = "/createGroupUser", method = {RequestMethod.POST})
    @ApiOperation(notes = "创建一个群组", value = "创建一个群组")
    public ResultMessage<String> createGroupUser(@RequestBody Map<String, Object> map) {
        String apiUrl = HuanXinConfig.url + "chatgroups/";
        try {
            String token = HuanXinUtil.getAccessToken();
            String result = OkHttpUtils.bodyPost(apiUrl)
                    .header("Authorization", "Bearer " + token)
                    .map(map).callForString();
            return new ResultMessage<>(result);
        } catch (Exception e) {
            logger.error("创建一个群组失败：" + e);
            return new ResultMessage<String>().toFailure("创建一个群组失败！");
        }
    }

    @RequestMapping(value = "/deleteGroup", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "删除群组", value = "删除群组")
    public ResultMessage<String> deleteGroup(@ApiParam("群组id") @RequestParam String group_id) {
        String apiUrl = HuanXinConfig.url + "chatgroups/" + group_id;
        try {
            String token = HuanXinUtil.getAccessToken();
            String result = OkHttpUtils.delete(apiUrl)
                    .header("Authorization", "Bearer " + token)
                    .callForString();
            return new ResultMessage<>(result);
        } catch (Exception e) {
            logger.error("删除群组失败：" + e);
            return new ResultMessage<String>().toFailure("删除群组失败！");
        }
    }

    @RequestMapping(value = "/addGroupUsers", method = {RequestMethod.POST})
    @ApiOperation(notes = "添加群组成员[批量]", value = "添加群组成员[批量]")
    public ResultMessage<String> addGroupUsers(String chatgroupid, @RequestBody Map<String, Object> usernames) {
        String apiUrl = HuanXinConfig.url + "chatgroups/" + chatgroupid + "/users";
        try {
            String token = HuanXinUtil.getAccessToken();
            String result = OkHttpUtils.bodyPost(apiUrl)
                    .header("Authorization", "Bearer " + token)
                    .map(usernames).callForString();
            return new ResultMessage<>(result);
        } catch (Exception e) {
            logger.error("添加群组成员[批量]失败：" + e);
            return new ResultMessage<String>().toFailure("添加群组成员[批量]失败！");
        }
    }

    @RequestMapping(value = "/getGroupUsers", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "获取群组所有成员", value = "获取群组所有成员")
    public ResultMessage<String> getGroupUsers(String group_id) {
        String apiUrl = HuanXinConfig.url + "chatgroups/" + group_id + "/users";
        try {
            String token = HuanXinUtil.getAccessToken();
            String result = OkHttpUtils.get(apiUrl)
                    .header("Authorization", "Bearer " + token)
                    .callForString();
            return new ResultMessage<>(result);
        } catch (Exception e) {
            logger.error("获取群组所有成员失败：" + e);
            return new ResultMessage<String>().toFailure("获取群组所有成员失败！");
        }
    }

    @RequestMapping(value = "/deleteGroupUser", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "移出群组成员[单个]", value = "移出群组成员[单个]")
    public ResultMessage<String> deleteGroupUser(String group_id, String username) {
        String apiUrl = HuanXinConfig.url + "chatgroups/" + group_id + "/users/" + username;
        try {
            String token = HuanXinUtil.getAccessToken();
            String result = OkHttpUtils.delete(apiUrl)
                    .header("Authorization", "Bearer " + token)
                    .callForString();
            return new ResultMessage<>(result);
        } catch (Exception e) {
            logger.error("移出群组成员[单个]失败：" + e);
            return new ResultMessage<String>().toFailure("移出群组成员[单个]失败！");
        }
    }

    @RequestMapping(value = "/addGroupUser", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "添加群组成员[单个]", value = "添加群组成员[单个]")
    public ResultMessage<String> addGroupUser(String group_id, String username) {
        String apiUrl = HuanXinConfig.url + "chatgroups/" + group_id + "/users/" + username;
        try {
            String token = HuanXinUtil.getAccessToken();
            String result = OkHttpUtils.bodyPost(apiUrl)
                    .header("Authorization", "Bearer " + token)
                    .callForString();
            return new ResultMessage<>(result);
        } catch (Exception e) {
            logger.error("添加群组成员[单个]失败：" + e);
            return new ResultMessage<String>().toFailure("添加群组成员[单个]失败！");
        }
    }

    @RequestMapping(value = "/getGroupDetails", method = RequestMethod.POST)
    @ApiOperation(notes = "获取群组详情", value = "获取群组详情")
    public ResultMessage<String> getGroupDetails(@RequestBody List<String> group_ids) {
        String apiUrl = HuanXinConfig.url + "chatgroups/";
        StringBuilder ids = new StringBuilder();
        for (String groupId : group_ids) {
            ids.append(ids.length() > 0 ? "," : "").append(groupId);
        }
        apiUrl = apiUrl + ids.toString();
        try {
            String token = HuanXinUtil.getAccessToken();
            String result = OkHttpUtils.get(apiUrl)
                    .header("Authorization", "Bearer " + token)
                    .callForString();
            return new ResultMessage<>(result);
        } catch (Exception e) {
            logger.error("获取群组详情失败：" + e);
            return new ResultMessage<String>().toFailure("获取群组详情失败！");
        }
    }

    @RequestMapping(value = "/modifyGroupDetails", method = RequestMethod.POST)
    @ApiOperation(notes = "修改群组信息", value = "修改群组信息")
    public ResultMessage<String> modifyGroupDetails(
            @ApiParam("群组id") @RequestParam String group_id,
            @ApiParam("待修改群组名称") @RequestParam(required = false) String groupname,
            @ApiParam("群组描述") @RequestParam(required = false) String description,
            @ApiParam("群组最大成员数") @RequestParam(required = false) String maxusers) {
        String apiUrl = HuanXinConfig.url + "chatgroups/" + group_id;
        Map<String, Object> map = new HashMap<>();
        map.put("groupname", groupname);
        map.put("description", description);
        map.put("maxusers", maxusers);
        try {
            String token = HuanXinUtil.getAccessToken();
            String result = OkHttpUtils.bodyPut(apiUrl)
                    .header("Authorization", "Bearer " + token)
                    .map(map).callForString();
            return new ResultMessage<>(result);
        } catch (Exception e) {
            logger.error("修改群组信息失败：" + e);
            return new ResultMessage<String>().toFailure("修改群组信息失败！");
        }
    }

}
